import { Controller, Get } from '@nestjs/common';
import { DatabaseService } from '../database/database.service.js';
import { RedisService } from '../redis/redis.service.js';

@Controller('health')
export class HealthController {
  constructor(
    private readonly databaseService: DatabaseService,
    private readonly redisService: RedisService,
  ) {}

  @Get()
  async check() {
    const timeout = <T>(ms: number, fallback: T): Promise<T> =>
      new Promise((resolve) => setTimeout(() => resolve(fallback), ms));

    const [dbOk, redisOk] = await Promise.all([
      Promise.race([
        this.databaseService.ping().then(() => true).catch(() => false),
        timeout(5000, false),
      ]),
      Promise.race([
        this.redisService.ping().then(() => true).catch(() => false),
        timeout(5000, false),
      ]),
    ]);

    return {
      status: dbOk && redisOk ? 'ok' : 'degraded',
      postgres: dbOk ? 'ok' : 'fail',
      redis: redisOk ? 'ok' : 'fail',
    } as const;
  }
}
